package com.dense.kuiniu.shelfcard.card.iccard;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.dense.kuiniu.shelfcard.R;

import java.util.ArrayList;
import java.util.List;

import D1000_Package.D1000_Serial;
import android_ttceserialport_api.TTCESerialPortFinder;

public class MainActivity extends Activity {

    private static final String[] StrComPort = {"COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8"};

    private Spinner ComSpinner;

    private ArrayAdapter<String> Comadapter;

    private static int Port = 0;
    private static byte MacAddr = 0x00;

    public static TTCESerialPortFinder m_SerialPortFinder = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_test);

        ComSpinner = (Spinner) findViewById(R.id.spinner1);
        final Button ConnectButton = (Button) findViewById(R.id.button1);
        final Button DisConnectButton = (Button) findViewById(R.id.button2);
        final Button SendCardButton = (Button) findViewById(R.id.button3);
        final Button SendCardToSensor2Button = (Button) findViewById(R.id.button4);
        final Button SendCardToReadPosButton = (Button) findViewById(R.id.button5);
        final Button SendCardToGetCardPosButton = (Button) findViewById(R.id.button6);
        final Button SendCardOutSideButton = (Button) findViewById(R.id.button7);
        final Button CheckSensorButton = (Button) findViewById(R.id.button8);
        final Button AllowBeepButton = (Button) findViewById(R.id.button9);
        final Button ForbidBeepButton = (Button) findViewById(R.id.button10);
        final Button ResetButton = (Button) findViewById(R.id.button11);
        final Button button19 = (Button) findViewById(R.id.button19);
        button19.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                byte[] cardNo = new byte[12];
                D1000_Serial.D1000_ReadCardNumber(MacAddr, cardNo);
                int length = cardNo.length;
            }
        });
        /*final Button ConnectButton=(Button)findViewById(R.id.button1);
        final Button DisConnectButton=(Button)findViewById(R.id.button2);
        final Button SendCardButton=(Button)findViewById(R.id.button3);
        final Button SendCardToSensor2Button=(Button)findViewById(R.id.button4);
        final Button SendCardToReadPosButton=(Button)findViewById(R.id.button5);
        final Button SendCardToGetCardPosButton=(Button)findViewById(R.id.button6);
        final Button SendCardOutSideButton=(Button)findViewById(R.id.button7);
        final Button CheckSensorButton=(Button)findViewById(R.id.button8);
        final Button AllowBeepButton=(Button)findViewById(R.id.button9);
        final Button ForbidBeepButton=(Button)findViewById(R.id.button10);
        final Button ResetButton=(Button)findViewById(R.id.button11);*/

        ConnectButton.setEnabled(true);
        DisConnectButton.setEnabled(false);

        m_SerialPortFinder = new TTCESerialPortFinder();
        String[] enterValue = m_SerialPortFinder.getAllDevicesPath();
        List<String> AllDevice = new ArrayList<String>();
        for (int i = 0; i < enterValue.length; i++) {
            AllDevice.add(enterValue[i]);
        }
        ArrayAdapter<String> aspnDevices = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, AllDevice);
        aspnDevices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ComSpinner.setAdapter(aspnDevices);

        if (AllDevice.size() > 0) {
            ComSpinner.setSelection(0);
        }
        ComSpinner.setVisibility(View.VISIBLE);

        ConnectButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //String StrPort="/dev/s3c2410_serial"+Port;//这个每个不同的测试机产品，文件位置不一样，请注意更新
                //String StrPort="/dev/ttyxrusb2";//这个每个不同的测试机产品，文件位置不一样，请注意更新
                String StrPort = ComSpinner.getSelectedItem().toString();
                int re = 0;
                byte i;
                int Baudate = 9600;
                re = D1000_Serial.D1000_CommOpen(StrPort);
                if (re == 0) {
                    for (i = 0; i < 16; i++) {
                        re = D1000_Serial.D1000_AutoTestMac((byte) i);
                        if (re == 0) {
                            MacAddr = i;
                            break;
                        }
                    }
                    if (i == 16 && MacAddr == 0) {
                        ShowMessage("设备连接失败，错误代码为：" + D1000_Serial.ErrorCode(re, 0));
                        D1000_Serial.D1000_CommClose();
                    } else {
                        ShowMessage("设备连接成功，设备地址为：" + MacAddr);
                        ConnectButton.setEnabled(false);
                        DisConnectButton.setEnabled(true);
                    }
                } else
                    ShowMessage("串口打开错误，错误代码为：" + D1000_Serial.ErrorCode(re, 0));
            }
        });

        DisConnectButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int re = 0;
                re = D1000_Serial.D1000_CommClose();
                if (re == 0) {
                    ConnectButton.setEnabled(true);
                    DisConnectButton.setEnabled(false);
                } else
                    ShowMessage("设备断开失败，错误代码为：" + D1000_Serial.ErrorCode(re, 0));
            }
        });

        SendCardButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int nRet;
                byte[] SendCmd = new byte[3];
                SendCmd[0] = 0x44;
                SendCmd[1] = 0x43;
                nRet = D1000_Serial.D1000_SendCmd(MacAddr, SendCmd, 2);
                if (nRet == 0) {
                    ShowMessage("发卡成功");
                } else
                    ShowMessage("发卡失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });

        SendCardToSensor2Button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int nRet;
                byte[] SendCmd = new byte[3];
                SendCmd[0] = 0x46;
                SendCmd[1] = 0x43;
                SendCmd[2] = 0x36;
                nRet = D1000_Serial.D1000_SendCmd(MacAddr, SendCmd, 3);
                if (nRet == 0) {
                    ShowMessage("发卡到传感器2位置成功");
                } else
                    ShowMessage("发卡到传感器2位置失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });

        SendCardToReadPosButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int nRet;
                byte[] SendCmd = new byte[3];
                SendCmd[0] = 0x46;
                SendCmd[1] = 0x43;
                SendCmd[2] = 0x37;
                nRet = D1000_Serial.D1000_SendCmd(MacAddr, SendCmd, 3);
                if (nRet == 0) {
                    ShowMessage("发卡到读卡位置成功");
                } else
                    ShowMessage("发卡到读卡位置失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });

        SendCardToGetCardPosButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int nRet;
                byte[] SendCmd = new byte[3];
                SendCmd[0] = 0x46;
                SendCmd[1] = 0x43;
                SendCmd[2] = 0x34;
                nRet = D1000_Serial.D1000_SendCmd(MacAddr, SendCmd, 3);
                if (nRet == 0) {
                    ShowMessage("发卡到取卡位置成功");
                } else
                    ShowMessage("发卡到取卡位置失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });

        SendCardOutSideButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int nRet;
                byte[] SendCmd = new byte[3];
                SendCmd[0] = 0x46;
                SendCmd[1] = 0x43;
                SendCmd[2] = 0x30;
                nRet = D1000_Serial.D1000_SendCmd(MacAddr, SendCmd, 3);
                if (nRet == 0) {
                    ShowMessage("发卡到卡口外成功");
                } else
                    ShowMessage("发卡到卡口外失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });

        CheckSensorButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                byte[] _States = new byte[4];
                int nRet;
                nRet = D1000_Serial.D1000_SensorQuery(MacAddr, _States);
                if (nRet == 0) {
                    ShowMessage("传感器状态查询成功，其值分别为：" + Integer.toHexString(_States[0] & 0xFF).toUpperCase() + " " + Integer.toHexString(_States[1] & 0xFF).toUpperCase() + " " + Integer.toHexString(_States[2] & 0xFF).toUpperCase() + " " + Integer.toHexString(_States[3] & 0xFF).toUpperCase());
                } else
                    ShowMessage("传感器状态查询失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });

        AllowBeepButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int nRet;
                byte[] SendCmd = new byte[3];
                SendCmd[0] = 0x42;
                SendCmd[1] = 0x45;
                nRet = D1000_Serial.D1000_SendCmd(MacAddr, SendCmd, 2);
                if (nRet == 0) {
                    ShowMessage("允许蜂鸣设置成功");
                } else
                    ShowMessage("允许蜂鸣设置失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });

        ForbidBeepButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int nRet;
                byte[] SendCmd = new byte[3];
                SendCmd[0] = 0x42;
                SendCmd[1] = 0x44;
                nRet = D1000_Serial.D1000_SendCmd(MacAddr, SendCmd, 2);
                if (nRet == 0) {
                    ShowMessage("禁止蜂鸣设置成功");
                } else
                    ShowMessage("禁止蜂鸣设置失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });

        ResetButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int nRet;
                byte[] SendCmd = new byte[3];
                SendCmd[0] = 0x52;
                SendCmd[1] = 0x53;
                nRet = D1000_Serial.D1000_SendCmd(MacAddr, SendCmd, 2);
                if (nRet == 0) {
                    ShowMessage("复位成功");
                } else
                    ShowMessage("复位失败，错误代码为：" + D1000_Serial.ErrorCode(nRet, 0));
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    private class ComPortListener implements OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
            // TODO Auto-generated method stub
            Port = arg2;
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    }

    public void ShowMessage(String str) {
        Builder builder = new Builder(MainActivity.this);
        builder.setTitle("Message");
        builder.setMessage(str);
        builder.setPositiveButton("OK", null);
        builder.show();
    }

    public void CopyByte(byte[] dest, byte[] ByteArray, int offset, int length) {
        for (int i = 0; i < length; i++)
            dest[i] = ByteArray[i + offset];
    }

    public String ByteToString(byte[] by) {
        String str = "";
        char ch = '\0';
        for (int i = 0; by[i] != '\0'; i++) {
            ch = (char) by[i];
            str += ch;
        }
        return str;
    }

    public void StringToByte(String str, byte[] by) {
        int len = str.length();
        if (len % 2 != 0) {
            ShowMessage("输入字符长度不为偶数，请重新确认....");
            return;
        } else {
            for (int i = 0; i < len / 2; i++)
                by[i] = (byte) (Integer.parseInt(str.substring(2 * i, 2 * i + 2), 16) & 0xFF);
            return;
        }
    }

    public byte String2Byte(String str) {
        byte by = 0x00;
        by = (byte) (Integer.parseInt(str.substring(0, 2), 16) & 0xFF);
        return by;
    }
}